package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import com.fasterxml.jackson.annotation.JsonFormat;

import io.minio.*;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) {
        String bucketname = minioProperties.getBucketName();
        String policy = """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(minioProperties.getBucketName());
        try{
            boolean b = client.bucketExists(BucketExistsArgs.builder().bucket(bucketname).build());
            if(!b){
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketname).build());
                client.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(bucketname).config(policy).build());
            }
            String filename = UUID.randomUUID()
                    + new SimpleDateFormat("yyyy-mm-dd").format(new Date())
                    +file.getOriginalFilename();
            client.putObject(PutObjectArgs.builder().bucket(bucketname)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .contentType(file.getContentType())
                            .object(filename)
                    .build()) ;
            System.out.println(minioProperties.getEndpoint()+"/"+bucketname+"/"+filename);
            return minioProperties.getEndpoint()+"/"+bucketname+"/"+filename;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }
}
